package com.tydic.portal.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import com.tydic.borderer.domain.BordererInfo;
import com.tydic.borderer.service.IBordererInfoService;
import com.tydic.common.core.domain.R;
import com.tydic.common.core.domain.model.LoginUser;
import com.tydic.common.core.enums.CarNumberBusinessTypeEnum;
import com.tydic.common.core.enums.ContractStatusEnum;
import com.tydic.common.core.enums.ProductGroupEnum;
import com.tydic.common.encrypt.utils.RSATools;
import com.tydic.common.mybatis.core.page.TableDataInfo;
import com.tydic.common.satoken.utils.LoginHelper;
import com.tydic.common.web.domain.bo.DetailBo;
import com.tydic.common.web.domain.bo.IdBo;
import com.tydic.order.domain.Order;
import com.tydic.order.domain.bo.OrderBatchBo;
import com.tydic.order.domain.bo.OrderReceiptBo;
import com.tydic.order.domain.bo.QueryOrderBo;
import com.tydic.order.domain.request.AgainHistoryByPageReq;
import com.tydic.order.domain.request.CheckSelectReq;
import com.tydic.order.domain.request.CreditRequest;
import com.tydic.order.domain.response.AppOrderResult;
import com.tydic.order.mapper.OrderMapper;
import com.tydic.order.service.IOrderService;
import com.tydic.product.domain.request.AppendCarNumberRequest;
import com.tydic.product.service.ICarNumberService;
import com.tydic.system.domain.ContractTemplate;
import com.tydic.system.service.IContractTemplateService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/portal/order")

public class OrderController {
    private final IOrderService orderService;
    private final IContractTemplateService contractTemplateService;
    private final ICarNumberService carNumberService;
    private final IBordererInfoService bordererInfoService;
    private final OrderMapper orderMapper;

    @PostMapping("singOrder")
    /**
     * 签署合同
     */
    public R singOrder(@Validated @RequestBody OrderBatchBo request) {
        List<String> companySignUrls = orderService.signOrder(request);
        return R.ok(companySignUrls);
    }


    @PostMapping("payOrder")
    /**
     * 支付订单
     */
    public R payOrder(@Validated @RequestBody OrderBatchBo request) {
        orderService.payOrder(request);
        return R.ok();
    }


    @PostMapping("modifyReceipt")
    /**
     * 修改收货信息
     */
    public R modifyReceipt(@Validated @RequestBody OrderReceiptBo modifyReceiptRequest) {
        orderService.modifyReceipt(modifyReceiptRequest);
        return R.ok();
    }

    @PostMapping("confirmDeliverProduct")
    /**
     * 确认发货
     */
    public R confirmDeliverProduct(@Validated @RequestBody OrderBatchBo request) {
        orderService.confirmDeliverProduct(request);
        return R.ok();
    }

    @PostMapping("confirmTakeGoods")
    /**
     * 确认收货
     */
    public R confirmTakeGoods(@Validated @RequestBody OrderBatchBo request) {
        orderService.confirmTakeGoods(request);
        return R.ok();
    }

    @PostMapping("cancelOrder")
    /**
     * 取消订单
     */
    public R cancelOrder(@Validated @RequestBody OrderBatchBo request) {
        orderService.cancelOrder(request);
        return R.ok();
    }

    @PostMapping("invoice")
    /**
     * 开发票
     */
    public R invoice(@Validated @RequestBody OrderBatchBo request) {
        orderService.invoice(request);
        return R.ok();
    }


    @PostMapping("settlementOrder")
    /**
     * 订单结算
     */
    public R settlementOrder(@Validated @RequestBody IdBo request) {
        orderService.settlementOrder(request);
        return R.ok();
    }

    @GetMapping("getNeedHandler")
    /**
     * 获取结算审核待办
     */
    public R getNeedHandler() {
        return R.ok(0);
    }

    @GetMapping("getEnterpriseNeedHandler")
    /**
     * 获取企业待签署
     */
    public R getEnterpriseNeedHandler() {
        return R.ok(0);
    }

    @GetMapping("getBordererNeedHandler")
    /**
     * 获取边民待签署
     */
    public R getBordererNeedHandler() {
        return R.ok(0);
    }

    @GetMapping("uploadAndUpdate")
    /**
     * 更新与上传
     */
    public R uploadAndUpdate(String orderId) {
//        orderService.uploadAndUpdate(orderId);

        ContractTemplate contractTemplate = new ContractTemplate();
        //contractTemplate.setTemplateFileId(templateFileId);
        contractTemplate.setTemplateStatus(ContractStatusEnum.USING.getStatus());
        return R.ok();
    }

    @GetMapping("createAndPush")
    /**
     * createAndPush
     */
    public R createAndPush(String orderCode, String orderId) {
        orderService.createAndPush(orderCode, orderId, null);
        return R.ok();
    }

    @GetMapping("getSignUrl")
    /**
     * getSignUrl
     */
    public R getSignUrl(String orderCode) {
        orderService.getSignUrl(orderCode);
        return R.ok();
    }

    /**
     * 下载合同
     */
    @GetMapping("getDoc")
    public R getDoc(String orderCode) {
        String url = orderService.getDoc(orderCode);
        return R.ok(url);
    }

    @PostMapping("/checkOrderSelect")
    /**
     * 查询没被选择的订单
     */
    public R checkOrderSelect(@Validated @RequestBody List<CheckSelectReq> request) {
        return R.ok(orderService.checkOrderSelect(request));
    }

    @PostMapping("/appendCarNumber")
    /**
     * 追加车辆信息
     */
    public R appendCarNumber(@Validated @RequestBody AppendCarNumberRequest appendCarNumberRequest) {
        carNumberService.save(appendCarNumberRequest.getProductId(), CarNumberBusinessTypeEnum.PRODUCT.getType(), appendCarNumberRequest.getCarNumbers());
        return R.ok();
    }


    @GetMapping("/getOrderSettlements")
    /**
     * 获取结算明细
     */
    public R getOrderSettlements(@NotBlank(message = "订单ID不能为空") @RequestParam("orderId") String orderId) {
        return R.ok(orderService.getOrderSettlements(orderId));
    }


    @PostMapping("/addCredit")
    public R addCredit(@Validated @RequestBody CreditRequest creditRequest) {
        try {
            Order order = orderMapper.selectById(creditRequest.getOrderCode());
            BordererInfo bordererInfo = bordererInfoService.getBordererInfoById(order.getBorderAgentId());
//        String apiUrl="http://localhost:8801/api/market2/receiveCreditInfo";
            String apiUrl = "https://dxhsmarket1.gx-dcloud.com/api/market2/receiveCreditInfo";
//        String apiUrl="http://localhost:8801/api/market2/receiveSaleOrderInfo";
            String platId = "80243b3e202d42dfab1c30ac9347a747";
//            RSA rsa = SecureUtil.rsa(IoUtil.readBytes(ResourceUtil.getStream("keystore/private.key")), IoUtil.readBytes(ResourceUtil.getStream("keystore/sys_public.cer")));
            RSATools rsaTools = new RSATools(ResourceUtil.getStream("keystore/private.key"), ResourceUtil.getStream("keystore/sys_public.cer"));
            JSONObject json = new JSONObject();
            json.put("platId", platId);
            json.put("customsCode", "7207");
            json.put("areaCode", "CNDOX720267");
            json.put("subjectNo", bordererInfo.getIdCardNumber());
            json.put("subjectName", bordererInfo.getName());
            json.put("score", 10 * (creditRequest.getLogisticsRating() + creditRequest.getServiceRating()));
            json.put("scoreRemark", creditRequest.getComment());
            String mv = rsaTools.encrypt(json.toJSONString());
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(apiUrl);
            post.addHeader("platId", platId);
            post.addHeader("requestId", IdUtil.fastSimpleUUID());
            post.addHeader("requestTime", DateUtil.format(new Date(), "yyyyMMddHHmmss"));
            post.setEntity(new StringEntity(mv, StandardCharsets.UTF_8));
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(res.getEntity());
                String response = rsaTools.decrypt(result);
                log.info("响应数据:{}", response);
            }
            return R.ok("评价商家成功");
        } catch (Exception e) {
            log.error("评价商家失败", e);
            return R.fail("评价商家失败");
        }
    }

    @PostMapping("getOrderDetail")
    /**
     * 查询订单详情
     */
    public R<AppOrderResult> getOrderDetail(@Validated @RequestBody DetailBo request) {
        return R.ok(orderService.getOrderDetail(request));
    }

    /**
     * 分页查询订单
     */
    @PostMapping("getOrderByPage")
    public R<TableDataInfo<Order>> getOrderByPage(@Validated @RequestBody QueryOrderBo request) {
        LoginUser currentUser = LoginHelper.getLoginUser();
        if (currentUser.isBordererAgent()) {
            request.setBorderAgentId(currentUser.getBorderInfoId());
            request.setGroupStatus(ProductGroupEnum.PARENT.getStatus());
        } else if (currentUser.isBorderer()) {
            request.setBordererInfoId(currentUser.getBorderInfoId());
            request.setGroupStatus(ProductGroupEnum.CHILD.getStatus());
        } else {
            request.setGroupStatus(ProductGroupEnum.PARENT.getStatus());
        }
        return R.ok(TableDataInfo.build(orderService.getOrderByPage(request)));
    }

    @PostMapping("getChildren")
    /**
     * 查询子订单
     */
    public R<List<AppOrderResult>> getChildren(@Validated @RequestBody DetailBo request) {
        return R.ok(orderService.getChildren(request));
    }

    /**
     * 预览合同
     */
    @GetMapping("getContractPageView")
    /**
     * 预览合同
     */
    public void getContractPageView(String orderCode, HttpServletResponse response) {
        orderService.getContractPageView(orderCode, response);
    }

    @PostMapping("/getAgentOrderHistory")
    /**
     * 查询代理子订单
     */
    public R<TableDataInfo<AppOrderResult>> getAgentOrderHistory(@Validated @RequestBody AgainHistoryByPageReq request) {
        return R.ok(TableDataInfo.build(orderService.getAgentOrderHistory(request)));
    }
}
